package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author: itheima
 * @create: 2022-05-13 12:10
 */
@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {

    /**
     * 根据条件分页查询频道列表
     *
     * @param dto 入参对象
     * @return
     */
    @Override
    public ResponseResult listByName(ChannelDto dto) {
        //1.构建查询对象QueryWrapper
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(dto.getName())) {
            queryWrapper.like(WmChannel::getName, dto.getName());
        }
        //2.构建分页对象
        IPage<WmChannel> page = new Page<>(dto.getPage(), dto.getSize());

        //3.执行查询
        page = this.page(page, queryWrapper);

        //4.封装响应结果
        long total = page.getTotal();
        List<WmChannel> records = page.getRecords();
        return new PageResponseResult(dto.getPage(), dto.getSize(), total, records);
    }

    /**
     * 保存频道
     *
     * @param entity 提交参数
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult saveChannel(WmChannel entity) {
        //1.给PO对象设置基础属性值
        entity.setIsDefault(false);
        entity.setOrd(1);
        if (entity.getStatus() == null) {
            entity.setStatus(false);
        }
        //2.调用保存方法
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmChannel::getName, entity.getName());
        int count = this.count(queryWrapper);
        if (count == 0) {
            this.save(entity);
            return ResponseResult.okResult();
        } else {
            return ResponseResult.errorResult(400, "该频道名称已经存在！");
        }
    }
}
